package vaadin.lab6;

import java.util.Locale;

import com.vaadin.data.Property;
import com.vaadin.data.util.PropertyFormatter;

@SuppressWarnings("serial")
public class CurrencyPropertyFormatter extends PropertyFormatter {

    public CurrencyPropertyFormatter(Property property) {
        super(property);
    }

    @Override
    public String format(Object value) {
        return String.format(Locale.US, "%1$.3f EUR", value);
    }

    @Override
    public Object parse(String formattedValue) throws Exception {
        return Double.parseDouble(removeCurrencySymbols(formattedValue));
    }

    public static String removeCurrencySymbols(String value) {
        String valueWithoutSymbol = value;
        if (value.endsWith("€")) {
            valueWithoutSymbol = value.substring(0, value.length() - 2);
        } else if (value.endsWith("EUR")) {
            valueWithoutSymbol = value.substring(0, value.length() - 4);
        }
        return valueWithoutSymbol;
    }

    @Override
    public Class<?> getType() {
        return String.class;
    }
}